/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.ulss.indexer.monitor;

import cn.ac.iie.ulss.indexer.runenvs.GlobalParas;
import cn.ac.iie.common.util.zk.ZkUtil;
import java.util.Random;
import org.apache.log4j.Logger;

/**
 *
 * 
 */
public class StatusUpdater implements Runnable {

    public static Logger log = Logger.getLogger(StatusUpdater.class.getName());

    @Override
    public void run() {
        String idxrecoveryPrefix = "/ulss/idxrecovery";
        int count = 0;
        int updateCount = 0;
        long bg = 0;
        Random r = new Random();
        while (true) {
            try {
                count++;
                updateCount++;
                Thread.sleep(2000);
                if (count >= 5) {
                    count = 0;
                    log.info("the update thread is active ...");
                }
                if (updateCount >= GlobalParas.updateStausMilis / 2000) {
                    updateCount = 0;
                    Thread.sleep(Math.abs(r.nextInt()) % 30000);
                    String fullPath = idxrecoveryPrefix + "/" + GlobalParas.hostName + "_" + GlobalParas.rocketConsumeGroupPrefix + "_consumergroup";
                    log.info("will update the status for  " + fullPath);
                    if (!ZkUtil.pathExists(GlobalParas.zkClient, fullPath)) {
                        log.info(fullPath + " does not exist,will create it ...");
                        ZkUtil.makeSurePersistentPathExists(GlobalParas.zkClient, fullPath);
                        ZkUtil.updatePersistentPath(GlobalParas.zkClient, fullPath, System.currentTimeMillis() + "");
                    } else {
                        bg = System.currentTimeMillis();
                        ZkUtil.updatePersistentPath(GlobalParas.zkClient, fullPath, System.currentTimeMillis() + "");
                        log.info("update " + fullPath + " ok，use milis " + (System.currentTimeMillis() - bg));
                    }
                }
                if (GlobalParas.isUpdaterShouldExit.get()) {
                    log.info("shut the status updater ok ... ");
                    break;
                }
            } catch (Exception ex) {
                log.error(ex, ex);
            }
        }
    }
}